/**
 * 调试助手工具
 * 用于清理localStorage和调试数据源问题
 */

// 查看localStorage中的种子数据
export const checkLocalStorageData = () => {
  const torrents = localStorage.getItem('starrypt_torrents');

  console.log('📊 localStorage种子数据检查:');

  if (!torrents) {
    console.log('✅ localStorage中没有种子数据');
    return { exists: false, count: 0 };
  }

  try {
    const parsed = JSON.parse(torrents);
    console.log('📁 localStorage中的种子数据:', parsed);
    console.log('📈 种子数量:', parsed.length);

    if (parsed.length > 0) {
      console.log('🔍 第一个种子:', parsed[0]);
      console.log('📝 种子标题列表:', parsed.map(t => t.title));
    }

    return { exists: true, count: parsed.length, data: parsed };
  } catch (error) {
    console.error('❌ localStorage数据解析失败:', error);
    return { exists: true, count: 0, error: true };
  }
};

// 清除所有StarRypt相关的localStorage数据
export const clearAllLocalStorageData = () => {
  const keys = Object.keys(localStorage);
  const starryptKeys = keys.filter(key => key.startsWith('starrypt_'));

  console.log('🗑️ 发现的StarRypt localStorage键:', starryptKeys);

  starryptKeys.forEach(key => {
    localStorage.removeItem(key);
    console.log(`✅ 已删除: ${key}`);
  });

  console.log('🎉 所有StarRypt数据已清除');
  return { cleared: starryptKeys.length, keys: starryptKeys };
};

// 只清除种子相关数据
export const clearTorrentsLocalStorage = () => {
  const removed = [];

  if (localStorage.getItem('starrypt_torrents')) {
    localStorage.removeItem('starrypt_torrents');
    removed.push('starrypt_torrents');
    console.log('✅ 已清除种子数据');
  }

  return { cleared: removed.length, keys: removed };
};

// 设置调试模式
export const enableDebugMode = () => {
  localStorage.setItem('starrypt_debug', 'true');
  console.log('🐛 调试模式已启用');

  // 在控制台添加调试命令
  window.StarRyptDebug = {
    checkLocalStorage: checkLocalStorageData,
    clearAll: clearAllLocalStorageData,
    clearTorrents: clearTorrentsLocalStorage,
    disableDebug: () => {
      localStorage.removeItem('starrypt_debug');
      console.log('🐛 调试模式已禁用');
    }
  };

  console.log('🛠️ 调试命令已添加到 window.StarRyptDebug');
  console.log('📝 可用命令: checkLocalStorage(), clearAll(), clearTorrents(), disableDebug()');
};

// 检查是否启用调试模式
export const isDebugMode = () => {
  return localStorage.getItem('starrypt_debug') === 'true';
};

// 初始化调试助手（在开发环境中自动启用）
export const initDebugHelper = () => {
  if (process.env.NODE_ENV === 'development' || window.location.search.includes('debug=true')) {
    enableDebugMode();

    // 自动检查localStorage
    setTimeout(() => {
      console.log('🔍 自动检查localStorage数据:');
      checkLocalStorageData();
    }, 1000);
  }
};

// 网络状态检查
export const checkNetworkStatus = async () => {
  console.log('🌐 检查网络状态...');

  try {
    const start = Date.now();
    const response = await fetch('/api/health', {
      method: 'GET',
      cache: 'no-cache'
    });
    const duration = Date.now() - start;

    console.log(`✅ 网络连接正常 (${duration}ms)`);
    return { online: true, latency: duration };
  } catch (error) {
    console.error('❌ 网络连接异常:', error);
    return { online: false, error: error.message };
  }
};

// OSS API状态检查
export const checkOssApiStatus = async () => {
  console.log('🔧 检查OSS API状态...');

  try {
    const start = Date.now();
    const response = await fetch('/oss/get_torrent', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      cache: 'no-cache'
    });
    const duration = Date.now() - start;

    if (response.ok) {
      const data = await response.json();
      console.log(`✅ OSS API正常 (${duration}ms)`, data);
      return { online: true, latency: duration, data };
    } else {
      console.error(`❌ OSS API错误: ${response.status} ${response.statusText}`);
      return { online: false, status: response.status, statusText: response.statusText };
    }
  } catch (error) {
    console.error('❌ OSS API连接失败:', error);
    return { online: false, error: error.message };
  }
};

// 综合诊断
export const runFullDiagnosis = async () => {
  console.log('🔬 开始全面诊断...');

  const results = {
    localStorage: checkLocalStorageData(),
    network: await checkNetworkStatus(),
    ossApi: await checkOssApiStatus(),
    timestamp: new Date().toISOString()
  };

  console.log('📋 诊断结果:', results);

  // 生成建议
  const suggestions = [];

  if (results.localStorage.exists && results.localStorage.count > 0) {
    suggestions.push('建议清除localStorage中的旧种子数据');
  }

  if (!results.network.online) {
    suggestions.push('网络连接异常，请检查网络连接');
  }

  if (!results.ossApi.online) {
    suggestions.push('OSS API不可用，请检查后端服务');
  }

  if (suggestions.length > 0) {
    console.log('💡 建议:', suggestions);
  } else {
    console.log('✅ 所有检查正常');
  }

  return { ...results, suggestions };
};

// 页面加载时自动初始化
if (typeof window !== 'undefined') {
  initDebugHelper();
}

export default {
  checkLocalStorageData,
  clearAllLocalStorageData,
  clearTorrentsLocalStorage,
  enableDebugMode,
  isDebugMode,
  initDebugHelper,
  checkNetworkStatus,
  checkOssApiStatus,
  runFullDiagnosis
}; 